package com.kou.controller;/**
 * @author SteinY
 * @create 2022-03-24 19:33
 * @description:
 */



import com.kou.utils.Constants;
import com.kou.utils.StrUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

/**
 * projectName:myshop2
 * author:SteinY
 * time:2022/3/24 19:33
 * description:
 */
@WebServlet("/base")
public class BaseServlet extends HttpServlet {
    @Override
    public void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("method");
        if (!StrUtils.empty(method)){
            method= Constants.INDEX;
        }

        Class<? extends BaseServlet> aClass = this.getClass();
        try {
            Method m = aClass.getMethod(method, HttpServletRequest.class, HttpServletResponse.class);
            Object result = m.invoke(this, req, resp);
            if(null != result){
                String r = (String) result;
                if (r.startsWith(Constants.FORWARD)||r.startsWith(Constants.REDIRECT)){
                    String[] p = r.split(Constants.FLAG);
                    if(p != null){
                        if(p.length == 2){
                            //判断    "forward:"    forward
                            if(Constants.FORWARD.startsWith(p[0])){
                                req.getRequestDispatcher(p[1]).forward(req,resp);
                            }else{
                                resp.sendRedirect(p[1]);
                            }
                        }else{
                            //返回字符串
                            resp.getWriter().println(p[0]);
                        }
                    }
                }else {
                    resp.getWriter().println(r);
                }


            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
    public String index(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //转发到首页  forward:为了告诉  //响应  我是内部转发
        //redirect : 代表重定向
        //不需要转发 只需要返回字符串 就可以了
        return Constants.FORWARD + "index.jsp";
    }

}